package com.hongxun.design.activitys;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.adapters.CodeSetModelAdapter;
import com.hongxun.design.adapters.CodelibraryConditionAdapter;
import com.hongxun.design.bean.CodeSetBean;
import com.hongxun.design.bean.CodelibraryConditionBean;
import com.hongxun.design.bean.MaterialBean;
import com.hongxun.design.bean.SetPointInfItemBean;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.jungong.model.RequestBeanNew;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.ui_listview.refreshlist.SwipeRefreshListView;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.lidroid.xutils.http.RequestParams;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by zerdoor_pc on 2016/5/18.
 * 点位设计-型号选择
 */
public class ChoiceModelActivity extends BaseActivity implements HeadSecond {
    /**
     * MString.click_in:选择点位点设
     * MString.click_out：引用平台点设
     */
    public String click;
    public String title;
    public String codeset_id, filter = "";
    SetPointInfItemBean bean;
    final int ADDADAPTER = 1;
    int type = View.GONE;
    // EditText serch_words;
    String codeset_version_id = "";
    SwipeRefreshListView codeset_list;
    Handler materialHandler;
    List<CodeSetBean> codeSetData;
    CodeSetModelAdapter codesetAdapter;
    static CodelibraryConditionAdapter adapter;
    Handler choiceModelHandler;
    boolean isTrue = false;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideWaitIngDialog();
            switch (msg.what) {
                case HttpStringUtil.SUCCESSED:
                    String valueOf = String.valueOf(msg.obj);
                    if (FastJsonUtil.JsonToCheck(valueOf)) {
                        RequestBeanNew aNew = FastJsonUtil.JsonToGetT(valueOf, new TypeReference<RequestBeanNew>() {
                        });
//                        String ver_ID = valueOf.substring(valueOf.lastIndexOf(":") + 1, valueOf.length() - 1).trim();
                        MyApp.currProject.setCodeset_version_id(aNew.getCodesetVersionid());
                        ToastShow.showShort(mActivity, "操作成功");
                    } else {
                        hideWaitIngDialog();
                        ToastShow.showShort(mActivity, "操作失败");
                    }
                    break;
                default:
                    ToastShow.showShort(mActivity, msg.obj + "");
                    break;
                case 99:
                    Integer integer = Integer.valueOf(String.valueOf(msg.obj));
                    if (MyApp.isOnLine) {
                        showWaitDialog(-1, "处理中...");
                        CodeSetBean setBean = codeSetData.get(integer);
                        RequestParams params = new RequestParams();
                        params.addBodyParameter("pro_id", MyApp.currProject.getStage_id());
                        params.addBodyParameter("pro_name", MyApp.currProject.getProject_name());
                        params.addBodyParameter("codesetid", setBean.getCodeset_id());
                        MyApp.HTTP.setProjectModel(handler, params);
                    } else {
                        ToastShow.showShort(getApplicationContext(), "离线情况下不能加入项目！");
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choicemodel);
        findBar();
        findView();
        initialization();
    }

    @Override
    public void findBar() {
        getIntentData();
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.choice_model_head);
        if (title.equals(MString.Material)) {
            headsecond_layout.initHeadPanel(DataUtil.getsecondbean(MString.SURE, View.GONE, R.color.bar_right, ListenerSet.back, title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        } else {
            switch (click) {
                case MString.click_in:
                    headsecond_layout.initHeadPanel(DataUtil.getsecondbean(MString.SURE, View.VISIBLE, R.color.bar_right, ListenerSet.back, "点位典型组装", R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
                    headsecond_layout.setClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            preservation();
                        }
                    });
                    break;
                case MString.click_out:
                    headsecond_layout.initHeadPanel(DataUtil.getsecondbean(MString.SURE, View.VISIBLE, R.color.bar_right, ListenerSet.back, "平台典型组装", R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
                    headsecond_layout.mRightTitle.setTextColor(getResources().getColor(R.color.login_yellow));
                    SetTypeface.set(headsecond_layout.mRightTitle, IconSourse.SEARCH);
                    headsecond_layout.mRightTitle.append(" " + MString.search);
                    headsecond_layout.mRightTitle.setVisibility(View.VISIBLE);
                    headsecond_layout.setClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            search();
                        }
                    });
                    break;
            }
        }

        if (MyApp.ReadOnly) {
            headsecond_layout.mRightTitle.setVisibility(View.INVISIBLE);
        }
    }

    @SuppressLint("NewApi")
    private void getIntentData() {
        Bundle bundle = getIntent().getExtras();
        click = bundle.getString(MString.CODE, "");
        switch (click) {
            case MString.click_in:
                type = View.VISIBLE;
                title = bundle.getString(MString.TYPE, "");
                codeset_id = bundle.getString(MString.codeset_id, "");
                filter = bundle.getString(MString.filter, "");
                codeset_version_id = MyApp.currProject.getCodeset_version_id();
                break;
            case MString.click_out:
                type = View.GONE;
                title = "典设";
//                title = "平台典型组装";
                isTrue = bundle.getBoolean(MString.TRUE);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mActivity = this;
        MyApp.activity = this;
    }

    @Override
    protected void findView() {
        switch (title) {
            case MString.ChoiceModelData:
                findView_ChoiceModelData();//典设
                break;
            case MString.Material:
                //findView_Material();//材料
                break;
        }
        super.findView();
    }

    @Override
    protected void initialization() {
        switch (title) {
            case MString.ChoiceModelData:
                initialization_ChoiceModelData();
                break;
            case MString.Material:
                // initialization_Material();
                break;
        }
        super.initialization();
    }

    /**
     * 搜索*
     */
    public void search() {
        refresdata();
    }

    String pt_id = "";
    String keyName = "";
    int startNum = 0;
    int addNum = MyApp.addNum;
    List<CodeSetBean> allbeans;

    public void getCodeSetList(int code) {
        pt_id = MyApp.currExploration.getPt_id();
        if (MyApp.isOnLine) {
            if (isTrue) {
                String trim = String.valueOf(adapter.getData().get(0).getValue()).trim();
                if (trim.isEmpty()) {
                    codeset_list.setRefreshing(false);
                    ToastShow.showShort(mActivity, "请先选择典设版本");
                    return;
                }
                MyApp.HTTP.getCodeSetList(choiceModelHandler, code, codeset_version_id, "", adapter.getData(), startNum, startNum + addNum, click, filter);
            } else
                MyApp.HTTP.getCodeSetList(choiceModelHandler, code, codeset_version_id, pt_id, adapter.getData(), startNum, startNum + addNum, click, filter);
        } else {
            String file = "";
            String id = "", pt = "";
            switch (click) {
                case MString.click_in:
                    file = MString.CodeSetList;
                    id = codeset_version_id;
                    pt = pt_id;
                    break;
                case MString.click_out:
                    String c = "";
                    String p = "";
                    for (CodelibraryConditionBean bean : adapter.getData()) {
                        if (bean.getNamecode().equals(MString.codeset_version_id)) {
                            c = bean.getValuecode();
                        } else if (bean.getNamecode().equals(MString.pt_id)) {
                            p = bean.getValuecode();
                        } else if (bean.getNamecode().equals(MString.name)) {

                        }
                    }

                    file = MString.CodeSetList;
                    id = c;
                    pt = p;
                    break;
            }

            for (CodelibraryConditionBean bean : adapter.getData()) {
                if (bean.getNamecode().equals(MString.name)) {
                    keyName = bean.getValuecode();
                }
            }
            String s = ShardPreferencesTool.getshare(this, file, "");
            if (allbeans == null) allbeans = new ArrayList<>();
            allbeans.clear();
            List<CodeSetBean> m = FastJsonUtil.JsonToData_CodeSetList(s);
            if (m.size() > 0) {
                for (CodeSetBean c : m) {
                    try {
                        if ((id.length() == 0 || c.getCodeset_version_id().equals(id)) && (pt.length() == 0
                                || c.getPt_id().equals(pt)) &&
                                c.getName().contains(keyName) && checKfilter(c.getKeyword())) {
                            allbeans.add(c);
                        }
                    } catch (Exception e) {
                    }
                }
            }
            choiceModelHandler.sendMessage(MyMessage.getMessage(2, code, 0, s));
        }

    }

    private boolean checKfilter(String keyword) {
        boolean flag = false;
        if (keyword == null || keyword.length() == 0) return true;
        if (filter == null || filter.length() == 0) return true;

        String[] filterArr = filter.split(",");
        String[] keywordArr = keyword.split(",");

        if (filterArr.length <= keywordArr.length) {
            for (int i = 0; i < filterArr.length; i++) {
                if (filterArr[i] != null && filterArr[i].length() > 0) {
                    if (keyword.contains(filterArr[i] + ",") || keyword.contains("," + filterArr[i])) {
                        flag = true;
                    } else {
                        return false;
                    }
                }
            }

        } else {
            flag = false;
        }

        return flag;
    }

    /**
     * 找到控件*
     */
    private void findView_ChoiceModelData() {
        codeset_list = (SwipeRefreshListView) findViewById(R.id.codeset_list);
        ListView condition_list = (ListView) findViewById(R.id.codelibrary_condition_list);
        /**条件**/
        switch (click) {
            case MString.click_in:
                adapter = new CodelibraryConditionAdapter(this, DataUtil.getCodelibraryConditionData_choice());
                break;
            case MString.click_out:
                adapter = new CodelibraryConditionAdapter(this, DataUtil.getCodelibraryConditionData());
                break;
        }
        condition_list.setAdapter(adapter);
        codeset_list.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresdata();
            }
        });
    }

    private void refresdata() {
        if (MyApp.NetWorkConnect) {
            startNum = 0;
            addNum = MyApp.addNum;
            getCodeSetList(HttpStringUtil.SUCCESSED);
        } else {
            //nx读取项目缓存点设
            String readM = ShardPreferencesTool.read(getApplicationContext(), MString.nxDsAdd, "", 3);
            List<CodeSetBean> beanList = JSON.parseArray(readM, CodeSetBean.class);
            if (beanList == null) beanList = new ArrayList<>();
            if (codeSetData == null) codeSetData = new ArrayList<>();
            else codeSetData.clear();
            codeSetData.addAll(beanList);
            choiceModelHandler.sendEmptyMessage(ADDADAPTER);
        }
    }

    @Override
    public void RefreshData() {
        super.RefreshData();
        search();
    }

    /**
     * 初始化*
     */
    /**
     * 查找典设handler*
     */
    private void initialization_ChoiceModelData() {
        AddHander_ChoiceModel();
        refresdata();
    }

    @Override
    public void addMore() {
        super.addMore();
        getCodeSetList(HttpStringUtil.ADDMROE);
    }

    private void AddHander_ChoiceModel() {
        choiceModelHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (codeSetData != null) {
                                codeSetData.clear();
                                codeSetData.addAll(FastJsonUtil.JsonToData_CodeSetList((String) msg.obj));
                            } else {
                                codeSetData = FastJsonUtil.JsonToData_CodeSetList((String) msg.obj);
                            }
                            choiceModelHandler.sendEmptyMessage(ADDADAPTER);
                            startNum = startNum + addNum;
                        } else {
                            codeset_list.setRefreshing(false);
                        }
                        break;
                    case 2:
                        int mnum = 0;
                        if (codeSetData != null) {
                            if (msg.arg1 == HttpStringUtil.SUCCESSED) {
                                codeSetData.clear();
                            } else {
                                mnum = Integer.parseInt(codeSetData.size() + "");
                            }
                            codeSetData.addAll(addData(startNum, startNum + addNum));
                        } else {
                            codeSetData = addData(startNum, startNum + addNum);
                        }
                        startNum = startNum + addNum;
                        if (msg.arg1 != HttpStringUtil.SUCCESSED) {
                            if (mnum < codeSetData.size()) {
                                startNum = startNum + addNum;
                            } else {
                                ToastShow.showShort(mActivity, "没有数据了");
                            }
                        }
                        choiceModelHandler.sendEmptyMessage(ADDADAPTER);
                        break;
                    case ADDADAPTER:
                        if (codesetAdapter == null) {
                            codesetAdapter = new CodeSetModelAdapter(codeSetData, mActivity);
                            codesetAdapter.setClick(click);
                            codesetAdapter.setHandler(handler);
                            codesetAdapter.setCodeset_id(codeset_id);
                            codeset_list.setAdapter(codesetAdapter);
                            codeset_list.setFragment(baseActivity);
                            codeset_list.setCanScroll(true);
                        } else {
                            codeset_list.update();
                            codeset_list.removeFooterView();
                        }
                        codeset_list.setRefreshing(false);
                        break;

                    case HttpStringUtil.ADDMROE:
                        int num = 0;
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (codeSetData != null) {
                                num = Integer.parseInt(codeSetData.size() + "");
                                codeSetData.addAll(FastJsonUtil.JsonToData_CodeSetList((String) msg.obj));
                            } else {
                                codeSetData = FastJsonUtil.JsonToData_CodeSetList((String) msg.obj);
                            }
                            choiceModelHandler.sendEmptyMessage(ADDADAPTER);
                            if (num < codeSetData.size()) {
                                startNum = startNum + addNum;
                            } else {
                                ToastShow.showShort(mActivity, "没有数据了");
                            }
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                }
            }
        };
    }


    private List<CodeSetBean> addData(int startNum, int endNum) {
        List<CodeSetBean> beans = new ArrayList<>();
        int i = 0;
        for (CodeSetBean p : allbeans) {
            if (endNum <= i) {
                return beans;
            }
            if (i >= startNum) {
                beans.add(p);
            }
            i++;
        }
        return beans;
    }

    /**
     * 保存典设*
     */
    private void preservation() {
        AddHander_Preservation();
        if (codesetAdapter == null || codesetAdapter.data == null || codesetAdapter.data.size() == 0 || ((List<CodeSetBean>) codesetAdapter.getChecked()).size() == 0) {
            ToastShow.showShort(mActivity, "典设不能为空！");
            return;
        }
        showWaitDialog(-1, "处理中...");
        Object checked = codesetAdapter.getChecked();
        if (MyApp.NetWorkConnect) {
            if (MyApp.isOnLine) {
                String codeset_id = ((List<CodeSetBean>) checked).get(0).getCodeset_id();
                MyApp.HTTP.SaveExpCodeset(materialHandler, HttpStringUtil.SUCCESSED, codeset_id, MyApp.currExploration.getExploration_id());
            } else {
                DotDesignActivity.setValue(MString.ChoiceModelData, checked);
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        materialHandler.sendEmptyMessage(1001);
                    }
                }, 1000);
            }
        } else {
            saveCodeSerBean(checked);
        }
    }

    //nx保存点位点设及其材料
    private void saveCodeSerBean(Object checked) {
        DotDesignActivity.setValue(MString.ChoiceModelData, checked);
        CodeSetBean setBean = ((List<CodeSetBean>) checked).get(0);
        //读取点设材料
        String key1 = MString.nxDsMaterial + setBean.getCodeset_id();
        String nxDsMaterial = ShardPreferencesTool.read(getApplicationContext(), key1, "", 3);
        List<MaterialBean> list = JSON.parseArray(nxDsMaterial, MaterialBean.class);
        //读取本地材料
        String keyMaterial = MString.nxPointMaterial + MyApp.currExploration.getExploration_id();
        String nxPointMaterial = ShardPreferencesTool.read(getApplicationContext(), keyMaterial, "", 3);
        List<MaterialBean> list1 = JSON.parseArray(nxPointMaterial, MaterialBean.class);
        //关联点设材料与点位
        if (list != null) {
            List<MaterialBean> listMaterial = new ArrayList<>();
            List<MaterialBean> listModular = new ArrayList<>();
            for (MaterialBean mbean : list) {
                if (mbean.getObj_type().equals("1")) {
                    listModular.add(mbean);
                } else {
                    if (list1 != null) {
                        for (MaterialBean bean : list1) {
                            if (mbean.getMaterial_number().equals(bean.getMaterial_number())) {
                                mbean.setMaterial_id(bean.getMaterial_id());
                                break;
                            }
                        }
                    }
                    listMaterial.add(mbean);
                }
            }
            //材料存储
            String key2 = MString.nxPointMaterial + MyApp.currExploration.getExploration_id();
            ShardPreferencesTool.save(getApplicationContext(), key2, FastJsonUtil.beanToJson(listMaterial), 3);
            //模块存储
            String key3 = MString.nxPointModel + MyApp.currExploration.getExploration_id();
            ShardPreferencesTool.save(getApplicationContext(), key3, FastJsonUtil.beanToJson(listModular), 3);
        }
        //关联点设与点位
        String key = MString.nxPointDs + MyApp.currExploration.getExploration_id();
        List<CodeSetBean> setBeans = new ArrayList<>();
        setBeans.add(setBean);
        ShardPreferencesTool.save(getApplicationContext(), key, FastJsonUtil.beanToJson(setBeans), 3);
        materialHandler.sendEmptyMessage(1001);
    }

    private void AddHander_Preservation() {
        materialHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            materialHandler.sendEmptyMessage(ADDADAPTER);
                        } else {
                            hideWaitIngDialog();
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case ADDADAPTER:
                        DotDesignActivity.setValue(MString.ChoiceModelData, codesetAdapter.getChecked());
                        new Timer().schedule(new TimerTask() {
                            @Override
                            public void run() {
                                materialHandler.sendEmptyMessage(1001);
                            }
                        }, 1000);
                        break;
                    case HttpStringUtil.ERROR:
                        hideWaitIngDialog();
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                    case 1001:
                        hideWaitIngDialog();
                        mActivity.onBackPressed();
                        break;

                }
            }
        };
    }


    public static void setValue(String type, Object value, String TYPENUM) {
        int position = Integer.parseInt(TYPENUM);
        adapter.setData(value, position);
    }

    @Override
    protected void onDestroy() {
        codesetAdapter = null;
        codeSetData = null;
        choiceModelHandler = null;
        materialHandler = null;
        super.onDestroy();
    }
}
